<?php
declare (strict_types = 1);

namespace app\command;

use GuzzleHttp\Client;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class Wiseman extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('wiseman')
            ->setDescription('the wiseman command');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);

        //获取分类数据
//        $cates = Db::name('category')->field('cid,cate_name')->where(['pid'=>0])->select();
//        if($cates){
//            //foreach($cates as $k=>$v){
//                //获取达人数据
//                //$this->getWiseman($v['cid']);
//                $this->getWiseman(16);
//            //}
//        }

        //获取author_id
        //$this->getAuthorId();

        //数据
        $this->getData();

        // 指令输出
        $output->writeln('wiseman');
    }

    protected function getWiseman($cid){
        $url = 'https://buyin.jinritemai.com/api/authorStatData/authorListLive';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://buyin.jinritemai.com',
            'Cookie'=>config('app.buyin_author.wiseCookie')
        ];
        $total = 3;
        for($i=1;$i<=$total;$i++){
            $client = new Client();
            $param = [
                'live_sale'=> [2,3,4,5],
                'indus_cate'=> [$cid],
                'pageSize'=> 20,
                'page'=> $i,
                //'refresh'=> 1,
                '_signature' => '_02B4Z6wo00901VVd2ZgAAIDCneEQhxBYMVFVWd0AADXmiyScHNj7rvr7PRijkJ3swBM.5OCKbo6PY9fq29xGLh0-azM5JTfOcQPUC7L8f0ut9dSmbsT.4gJk-tdSuqOQjrRqbaW7XFSMnjENbb'
            ];
            echo '第:'.$i,'页';
            $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);
            try {
                $result = json_decode($response->getBody()->getContents(), true);

//                echo '<pre>';print_r($result);exit;
                if($result['code'] == 0){

                    if(isset($result['data']['list']) && $result['data']['list']){
                        $total = ceil($result['data']['total'] / $param['pageSize']);
                        echo 'total:'.$total;
                        foreach($result['data']['list'] as $k=>$v){
                            //达人信息
                            $info = $this->getDyAccount($v['uid']);
                            //达人数据
                            $infoData = $this->getAuthor($v['uid']);
                            $data = [
                                'uid' => $v['uid'],
                                'nickname' => $v['nickname'],
                                'avatar' => $v['avatar'],
                                'fans_num' => $v['fans_sum'],
                                'gender' => $v['gender'],
                                'dy_id' => $info['account_douyin'],//抖音id
                                'author_level' => $v['author_level'],
                                'goods_main_cate' => isset($v['goods_main_cate']) && isset($v['goods_main_cate']) ? json_encode($v['goods_main_cate'], JSON_UNESCAPED_UNICODE) : '',
                                'content_cate' => isset($v['content_cate']) && isset($v['content_cate']) ? json_encode($v['content_cate'], JSON_UNESCAPED_UNICODE) : '',
                                'link_num' => 0, //点赞数
                                'works_num' => 0, //作品数
                                'product_num' => $infoData['promotion_sum'], //作品数
                                'sale_num' => 0, //销售数量
                                'volume' => 0, //总销售额
                                'city' => $v['city'],
                                'phone' => $v['contact_phone'],
                                'wechat' => $v['contact_wechat'],
                                'join_price' => $info['join_price'],
                                'special_price' => $info['special_price'],
                                'introduction' => $info['introduction'],
                                'share_url_douyin' => $info['share_url_douyin'],
                                'score' => $info['score'],
                                'cid' => $cid,
                                'create_time' => time(),
                            ];

                            //echo '<pre>';print_r($data);exit;
                            $res = Db::name('wiseman')->where(['dy_id'=>$info['account_douyin']])->find();

                            if(!$res){
                                Db::name('wiseman')->insert($data);
                            }else{
                                Db::name('wiseman')->where(['dy_id'=>$info['account_douyin']])->update($data);
                            }
                            echo '.';

                        }
                    }
                }else{
                    Log::info('调用接口失败' . $result['code'].'--'.$result['msg']);
                    exit;
                }
                sleep(1);
            }catch (\Exception $e){
                Log::info('调用接口失败' . $result['code']);
                continue;
            }

        }


    }

    protected function getDyAccount($uid){
        $url = 'https://buyin.jinritemai.com/api/authorStatData/authorProfile';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://buyin.jinritemai.com',
            'Cookie'=>config('app.buyin_author.wiseCookie')
        ];
        $param = [
            'uid'=> $uid,
            'works_type'=> 1,
            'special_price_id'=> '',
        ];

        $data = [
            'account_douyin' => '',
            'join_price' => 0,
            'special_price' => 0,
            'share_url_douyin' => '',
            'introduction' => '',
            'score' => '',
        ];

        $client = new Client();
        $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);
        $result = json_decode($response->getBody()->getContents(), true);

        if ($result['code'] == 0) {
            if($result['data']){
                $data['account_douyin'] = $result['data']['account_douyin'];
                $data['join_price'] = $result['data']['join_price'];
                $data['special_price'] = $result['data']['special_price'];
                $data['share_url_douyin'] = $result['data']['share_url_douyin'];
                $data['introduction'] = $result['data']['introduction'];
                $data['score'] = $result['data']['score'];
            }
        }

        return $data;
    }

    protected function getAuthor($uid){
        $data = [
            'promotion_sum' => 0,
        ];

        $url = 'buyin.jinritemai.com/api/authorStatData/authorOverview';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://buyin.jinritemai.com',
            'Cookie'=>config('app.buyin_author.wiseCookie')
        ];
        $param = [
            'uid'=> $uid,
            'works_type'=> 1,
            'category'=> 0,
        ];

        $client = new Client();
        $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);
        $result = json_decode($response->getBody()->getContents(), true);

        if ($result['code'] == 0) {
            if($result['data']){
                $data['promotion_sum'] = isset($result['data']['d30']['promotion_sum']) ? $result['data']['d30']['promotion_sum'] : 0;
            }
        }

        return $data;
    }

    protected function getAuthorId(){
        $wiseman = Db::name('wiseman')->field('id,dy_id')->select();
        $url = 'https://api-service.chanmama.com/v1/search';
        if($wiseman){
            $wiseman = $wiseman->toArray();
            foreach($wiseman as $k=>$v){
                $headers = [
                    'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
                    'Referer' => 'https://www.chanmama.com/',
                ];
                $param = [
                    'keyword' =>  $v['dy_id']
                ];
                try{
                    $client = new Client();
                    $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);
                    $result = json_decode($response->getBody()->getContents(), true);
                    if($result['errCode'] == 0){
                        if(isset($result['data']['authors']) && $result['data']['authors']){
                            Db::name('wiseman')->where(['dy_id'=>$v['dy_id']])->update(['author_id'=>$result['data']['authors'][0]['author_id']]);
                        }
                    }else{
                        Log::info('调用接口失败' . $result['errCode']);
                        continue;
                    }

                }catch (\Exception $e){
                    Log::info('调用接口失败' . $e->getMessage());
                    continue;
                }
                echo '.';
                if($k % 100 == 0) sleep(1);
            }
        }
    }

    protected function getData(){
        $wiseman = Db::name('wiseman')->field('id,author_id')->select();
        $url = 'https://www.doudouxia.com/data-center/douyin/author/history';
        if($wiseman){
            $wiseman = $wiseman->toArray();
            foreach($wiseman as $k=>$v){
                $author_id = $v['author_id'];
                if($author_id != ''){
                    $headers = [
                        'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
                        'Referer' => ' https://servicewechat.com/wx0ba7924743cbcc26/121/page-frame.html',
                    ];
                    $param = [
                        'id' =>$author_id
                    ];
                    try{
                        $client = new Client();
                        $response = $client->request('GET', $url, ['query'=>$param,'timeout'=>5, 'headers'=>$headers]);
                        $result = json_decode($response->getBody()->getContents(), true);
                        if(isset($result['result'])){
                            if(isset($result['result']['author']) && $result['result']['author']){
                                $data = [
                                    'fans_num' => $result['result']['author']['follower_count'],
                                    'link_num' => $result['result']['author']['total_favorited'],
                                    'works_num' => $result['result']['author']['aweme_count'],
                                    'sec_uid' => $result['result']['author']['sec_uid'],
                                ];
                                Db::name('wiseman')->where(['author_id'=>$author_id])->update($data);
                            }
                        }else{
                            Log::info('调用接口失败-' .$author_id);
                            continue;
                        }

                    }catch (\Exception $e){
                        Log::info('调用接口失败' . $e->getMessage());
                        continue;
                    }
                }

                echo '.';
                if($k % 500 == 0) sleep(1);
            }
        }
    }
}
